﻿// Initialize app
var myApp = new Framework7({
    //template7Pages: true, //enable Template7 rendering for pages
    //Specify templates/pages data
    precompileTemplates: true,
    template7Pages: true,
});
// If we need to use custom DOM library, let's save it to $$ variable:
var $$ = Framework7.$;

// Add view
var mainView = myApp.addView('.view-main', {
    // Because we want to use dynamic navbar, we need to enable it for this view:
    dynamicNavbar: true,
})

var currentPage = 1;
var alreadyAlert = true;

var toolbarPara = {};//导航栏参数

$$(document).on('pageAfterAnimation', function (e) {
    var pageName = e.detail.page.name;
    if (pageName === 'index') {
        shijian();
        var toolbarHtml = '<div class="toolbar-inner" style="background-color:white;">' +
            '     <a class="button" id="toolbar-button" onclick="handler()" style="width:60%;margin-left: 20%;background-color:#509AF1;color:white;height:40px;line-height:40px;border-radius:2px;">搜索</a>' +
            '</div>';
        $("#index-tool").html(toolbarHtml);
        mainView.showToolbar();
    } else if (pageName === 'search') {
        var typeId = $("#search-typeId").val();
        var startTime = $("#search-startTime").val();
        var endTime = $("#search-endTime").val();
        var personNumber = $("#search-personNumber").val();
        toolbarPara.chartered_typeId = typeId;
        toolbarPara.startTime = startTime;
        toolbarPara.endTime = endTime;
        toolbarPara.personNumber = personNumber;
        $("#index-tool").html(newToolbar(toolbarPara));
        myApp.showToolbar()
    } else if (pageName === 'detail') {
       App.detailBottomMenu();
    }
});
$$(document).on('pageInit', function (e) {
    // Get page data from event data
    var page = e.detail.page;
    if (page.name === 'index') {
        App.cityInputCenter();
        $.post(Constant.ctx("/mulanweb/common/city/search"),{PageSize:20,PageNumber:1},function(info){
            var option = [];
            for(var i in info.DataList){
                option[i] = '<option value="'+info.DataList[i].Id+'">'+info.DataList[i].NameCn+'</option>';
            }
            $("#cityId").html(option.join(" "));
        });

        tu();
    } else if (page.name === 'search') {
        totalPage = 1;
        loadSearchPage();
    } else if (page.name === 'detail') {
        App.loadDetailPage();
    } else if(page.name === 'seller-shop'){
        App.loadSellerShop();
    }else if (page.name === 'reserve') {
        App.loadCharteredReservePage();
    }
})
var totalPage = 1;
//提示 已经没有内容了

//AddType 不等于null 表示刷新，否则表示无限加载
function addSearchResult(para, AddType) {
    if (para.PageNumber > totalPage) {
        if (alreadyAlert) {
            Constant.alertNotification("往下已没有更多内容了！");
            $$('.infinite-scroll-preloader').remove();
            alreadyAlert = false;
        }
        return false;
        App.hideLoading();
    }
    $.ajax({
        url: Constant.ctx("/mulanweb/common/chartered/search"),
        async: false,
        type: "post",
        dataType: "json",
        data: para,
        success: function (data) {
            if (data.ReturnCode == 1) {
                var template = $('#contentSearchDataList').html();
                var compiledTemplate = Template7.compile(template);
                var amount = $("#search-amount").val()
                data["amount"] = amount;
                var htmlStr = compiledTemplate(data);
                totalPage = data.TotalPage;
                if (AddType) {
                    $("#queryResultList").html(htmlStr);
                    currentPage = 1;
                } else {
                    $("#queryResultList").append(htmlStr);
                }
                if (data.TotalPage <= data.PageNumber) {
                    $$('.infinite-scroll-preloader').remove();
                }
            }
            App.hideLoading();
        }
    }, para, function (data) {
    });
}
var SearchDataPara = {};
function loadSearchPage() {
    var cityId = $("#search-cityId").val();
    var typeId = $("#search-typeId").val();
    var startTime = $("#search-startTime").val();
    var endTime = $("#search-endTime").val();
    var personNumber = $("#search-personNumber").val();
    SearchDataPara.PageSize = 10;
    SearchDataPara.PageNumber = 1;
    SearchDataPara.cityId = cityId;
    SearchDataPara.typeId = typeId;
    SearchDataPara.startTime = startTime;
    SearchDataPara.endTime = endTime;
    SearchDataPara.receptionNumber = personNumber;
    //上拉无限加载
    var loading = false;
    var PageSize = 10;
    var PageNumber = 1;
    $$('.infinite-scroll').on('infinite', function () {
        if (loading) return;
        // 设置flag
        loading = true;
        currentPage = currentPage + 1;
        SearchDataPara.PageNumber = currentPage;
        addSearchResult(SearchDataPara);
        loading = false;
    });

    //下拉刷新  添加'refresh'监听器
    $$('.pull-to-refresh-content').on('refresh', function (e) {
        SearchDataPara.PageNumber = 1;
        SearchDataPara.PageSize = 10;
        if (!alreadyAlert) {
            alreadyAlert = true;
            var html = '<div class="infinite-scroll-preloader">' +
                '<div class="preloader" style="margin-left:48%"></div>' +
                '</div>';
            $$('.page-content').append(html);
        }
        $$('div[name=items]').remove();
        addSearchResult(SearchDataPara, "refresh");
        myApp.pullToRefreshDone();
    });
    addSearchResult(SearchDataPara, "refresh");
}


function changeOrder(orderBy, thisSpan) {

    //$(this).toggleClass("search-data-order-by");
    var label = $(".row .indexToolbar");
    if ($(thisSpan).hasClass("search-data-order-by")) {

    } else {
        for (var tt = 0; tt < label.length; tt++) {
            var src = $(label[tt]).children("img").attr("src");
            $(label[tt]).removeClass("search-data-order-by");
            $(label[tt]).children("img").attr("src", src.replace("-top-", "-bottom-"));
        }
        $(thisSpan).addClass("search-data-order-by");
        $(thisSpan).children("img").attr("src", src.replace("-bottom-", "-top-"));
    }
    var cityId = $("#search-cityId").val();
    var typeId = $("#search-typeId").val();
    SearchDataPara.PageSize = 10;
    SearchDataPara.PageNumber = 1;
    SearchDataPara.orderBy = orderBy;
    SearchDataPara.cityId = cityId;
    SearchDataPara.typeId = typeId;
    addSearchResult(SearchDataPara, "refresh");
}

function jh() {
    var personNumber = $("#personNumber").text();
    if (personNumber > 1) {
        personNumber--;
    }
    if (personNumber == 1) {
        $("#jianhao").attr("src", $("#jianhao").attr("src").replace("jianhao", "jianhao_no")).attr("disabled", "disabled");
        $("#jianhao");
    } else {
        $("#jiahao").attr("src", $("#jiahao").attr("src").replace("jiahao_no", "jiahao")).removeAttr("disabled");
    }
    $("#personNumber").text(personNumber);
}
function jiah() {
    var personNumber = $("#personNumber").text();
    if (personNumber < 10) {
        personNumber++;
    }
    if (personNumber == 10) {
        $("#jiahao").attr("src", $("#jiahao").attr("src").replace("jiahao", "jiahao_no")).attr("disabled", "disabled");
    } else {
        $("#jianhao").attr("src", $("#jianhao").attr("src").replace("jianhao_no", "jianhao")).removeAttr("disabled");
    }
    $("#personNumber").text(personNumber);
}
function qingkong() {
    $(pickerInline.input).val("");
}
function shijian() {
    $("#picker-date-container").html("");
    var pickerInline;
    $(".datetime").click(function () {
        myApp.pickerModal('.picker-info');
        if (!pickerInline) {
            var today = new Date();
            pickerInline = myApp.picker({
                input: '#picker-date',
                container: '#picker-date-container',
                toolbar: false,
                rotateEffect: true,
                closeByOutsideClick: true,
                value: [today.getFullYear(), today.getMonth(), today.getDate(), today.getHours(), (today.getMinutes() < 10                ? '0' + today.getMinutes() : today.getMinutes())],

                onChange: function (picker, values, displayValues) {
                    var daysInMonth = new Date(picker.value[0], picker.value[1] * 1 + 1, 0).getDate();
                    if (values[2] > daysInMonth) {
                        picker.cols[2].setValue(daysInMonth);
                    }
                },
                onClose:function(p){
                    alert("关闭");
                },

                formatValue: function (p, values, displayValues) {
                    return values[0] + '-' + displayValues[1] + '-' + values[2] + ' ' + values[3] + ':' + values[4];
                },

                cols: [
                    // Years
                    {
                        values: (function () {
                            var arr = [];
                            for (var i = 1950; i <= 2030; i++) {
                                arr.push(i);
                            }
                            return arr;
                        })(),
                    },
                    // Months
                    {
                        values: ('0 1 2 3 4 5 6 7 8 9 10 11').split(' '),
                        displayValues: ('1 2 3 4 5 6 7 8 9 10 11 12').split(' '),
                        textAlign: 'center'
                    },
                    // Days
                    {
                        values: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31],
                    },
                    // Space divider
                    {
                        divider: true,
                        content: '  '
                    },
                    // Hours
                    {
                        values: (function () {
                            var arr = [];
                            for (var i = 0; i <= 23; i++) {
                                arr.push(i);
                            }
                            return arr;
                        })(),
                    },
                    // Divider
                    {
                        divider: true,
                        content: ':'
                    },
                    // Minutes
                    {
                        values: (function () {
                            var arr = [];
                            for (var i = 0; i <= 59; i++) {
                                arr.push(i < 10 ? '0' + i : i);
                            }
                            return arr;
                        })(),
                    }
                ]
            });
        }
        pickerInline.input = "#" + $(this).attr("id");
    });
}
function tu() {
    $("table tr td img").on("click", function () {
        var src = $(this).attr("src");
        if (src.indexOf("yes") != -1) {
            ///$(this).attr("src",src.replace("true","false"));
        } else {
            var label = $("table tr td img");
            for (var tt = 0; tt < label.length; tt++) {
                var ttSrc = $(label[tt]).attr("src");
                if (ttSrc.indexOf("yes") != -1) {
                    $(label[tt]).attr("src", ttSrc.replace("yes", "no"));
                }
            }
            $(this).attr("src", src.replace("no", "yes"));
            if (src.indexOf("fulltime") != -1) {
                //表示全日包车
                $("#queryType").val(8);
            } else if (src.indexOf("transfer") != -1) {
                //表示接送机
                $("#queryType").val(10);
            } else if (src.indexOf("accompany") != -1) {
                //陪游
                $("#queryType").val(11);
            } else {
                //表示计时包车
                $("#queryType").val(9);
            }
        }

    });

}

function newToolbar(para) {
    var url = '#';
    var photoStr = "";
    if (para.chartered_typeId == 8) {
        url = Constant.cdnContentPath+'/static/image/chartered/quanribaoche.png';
        photoStr="全日包车";
    } else if (para.chartered_typeId == 9) {
        url = Constant.cdnContentPath+'/static/image/chartered/jishibaoche.png';
        photoStr="计时包车";
    } else if (para.chartered_typeId == 10) {
        url = Constant.cdnContentPath+'/static/image/chartered/baojieji.png';
        photoStr="接送机";
    } else if (para.chartered_typeId == 11) {
        url = Constant.cdnContentPath+'/static/image/chartered/daoyou.png';
        photoStr="导游";
    }
    var moduleEvaluatesHtml = $("#charteredinfo").html();
    var compiledTemplate = Template7.compile(moduleEvaluatesHtml);
    var newEvaluatesHtml = compiledTemplate({
        startTime: para.startTime,
        endTime: para.endTime,
        picture: url,
        photoStr:photoStr,
        personNumber: para.personNumber
    });
    return newEvaluatesHtml;
}

